<?php
declare (strict_types = 1);

namespace app\middleware;
use app\Request;
use Closure;
use think\facade\Cache;
use think\facade\Cookie;
use think\Response;

class Check
{
    public array $noLoginAction = ['login'];

    public const COOKIE_KEY = 'wol_user';
    public const SESSION_KEY = 'login';
    /**
     * 处理请求
     *
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (!in_array($request->action(), $this->noLoginAction)) {
            $cookie = Cookie::get(self::COOKIE_KEY);
            $isCookieExist = !empty($cookie) ? Cache::get($cookie) : null;
            if (empty($isCookieExist) && empty(session(self::SESSION_KEY))) {
                return redirect('/login.html');
            }
            $request->isLogin = true;
        }

        return $next($request);
    }
}
